package com.huayi.gg.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.huayi.gg.R;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ImageHelper {
	private static final int FREE_SD_SPACE_NEEDED_TO_CACHE = 10;
	private static final String TAG = "yang";
	private Bitmap mBitmap;
	private final static String ALBUM_PATH = Environment
			.getExternalStorageDirectory() + "/download/";
	private OkHttpClient okHttpClient;
	public ImageHelper(){


	}

	/*
	 * �õ�ͼƬ�ֽ��� �����С
	 */
	private  static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		inStream.close();
		return outStream.toByteArray();
	}
	public Bitmap downloadImage(String url) throws IOException {

		Request request = new Request.Builder()
				.url(url)
				.build();
		Response response = okHttpClient.newCall(request).execute();

		return BitmapFactory.decodeStream(response.body().byteStream());
	}
	public  static byte[] downloadImage_tobyte(String url) throws Exception {

		Request request = new Request.Builder()
				.url(url)
				.build();
		OkHttpClient okHttpClient= new OkHttpClient();
		Response response = okHttpClient.newCall(request).execute();

		return readStream(response.body().byteStream());
	}

	private Bitmap getImage(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setReadTimeout(10 * 1000);
        conn.setConnectTimeout(10 * 1000);
        conn.setRequestMethod("GET");
        InputStream is = null;
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            is = conn.getInputStream();
        } else {
            is = null;
        }
        if (is == null){
            throw new RuntimeException("stream is null");
        } else {
            try {
                byte[] data=readStream(is);
                if(data!=null){
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    return bitmap;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            is.close();
            return null;
        }
    }

	
	public void loadImage(final ImageView imageView, final String urlString,
                          final boolean useCache) {

		imageView.setImageResource(R.drawable.loading);

	

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				imageView.setImageDrawable((Drawable) message.obj);
			}
		};

		Runnable runnable = new Runnable() {
			public void run() {
				Drawable drawable = null;
				try {
					String filename =getfilename(urlString);
					File dirFile = new File(ALBUM_PATH+filename);
					
					
					if (!dirFile.exists()) {
						mBitmap =getImage(urlString);
						drawable =new BitmapDrawable(mBitmap);
						if (drawable != null) {
							if (useCache) {
								saveFile(mBitmap, filename);
							}
						}
					}else{
						drawable= BitmapDrawable.createFromPath(dirFile.getPath());
					
					}
					
				} catch (Exception e) {
					Log.e(this.getClass().getSimpleName(),
							"Image download failed", e);
					// Show a "download fail" image
					drawable = imageView.getResources().getDrawable(
							R.drawable.loading);
				}

				// Notify UI thread to show this image using Handler
				Message msg = handler.obtainMessage(1, drawable);
				handler.sendMessage(msg);
			}
		};
		new Thread(runnable).start();

	}

	private String getfilename(String url) {
		return url.substring(url.lastIndexOf("/") + 1);
	}

	/*
	 * �����ļ�
	 */
	protected void saveFile(Bitmap bm, String fileName) throws IOException {
		File dirFile = new File(ALBUM_PATH);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		Log.e(TAG, ALBUM_PATH + fileName);
		File myCaptureFile = new File(ALBUM_PATH + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
	}
	/** storage location: sdcard/Android/data/packagename
	 *
	 * @param context
	 * @param fileName
	 * @param image
	 * @param environmentType
	 * @param dirName
	 */
	public static  void saveImage2SandBox(Context context, String fileName, byte[] image, String environmentType, String dirName) {
		File standardDirectory;
		String dirPath;

		if (TextUtils.isEmpty(fileName) || 0 == image.length) {
			Log.e(TAG, "saveImage2SandBox: fileName is null or image is null!");
			return;
		}

		if (!TextUtils.isEmpty(environmentType)) {
			standardDirectory = context.getExternalFilesDir(environmentType);
		} else {
			standardDirectory = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
		}

		if (!TextUtils.isEmpty(dirName)) {
			dirPath = standardDirectory + "/" + dirName;
		} else {
			dirPath = String.valueOf(standardDirectory);
		}

		File imageFileDirctory = new File(dirPath);
		if (!imageFileDirctory.exists()) {
			if (!imageFileDirctory.mkdir()) {
				Log.e(TAG, "saveImage2SandBox: mkdir failed! Directory: " + dirPath);
				return;
			}
		}

//        if (queryImageFromSandBox(context, fileName, environmentType, dirName)) {
//            Log.e(TAG, "saveImage2SandBox: The file with the same name already exists！");
//            return;
//        }

		try {
			File imageFile = new File(dirPath + "/" + fileName);
			FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
			fileOutputStream.write(image);
			fileOutputStream.flush();
			fileOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** storage location: sdcard/Android/data/packagename
	 *
	 * @param context
	 * @param fileName
	 * @param environmentType
	 * @param dirName
	 * @return
	 */
	public static byte[] loadImageFromSandBox(Context context, String fileName, String environmentType, String dirName) {
		String type;
		String dirPath;

		if (TextUtils.isEmpty(fileName)) {
			Log.e(TAG, "loadImageFromSandBox: fileName is null");
			return null;
		}

		if (!TextUtils.isEmpty(environmentType)) {
			type = environmentType;
		} else {
			type = Environment.DIRECTORY_PICTURES;
		}

		File standardDirectory = context.getExternalFilesDir(type);
		if (null == standardDirectory) {
			return null;
		}

		if (!TextUtils.isEmpty(dirName)) {
			dirPath = standardDirectory + "/" + dirName;
		} else {
			dirPath = String.valueOf(standardDirectory);
		}

		File direction = new File(dirPath);
		File[] files = direction.listFiles();
		if (files != null) {
			for (File file : files) {
				String name = file.getName();   // 此处的文件名不带路径
				if (file.isFile() && fileName.equals(name)) {
					try {
						InputStream inputStream = new FileInputStream(file);
						byte[] image = new byte[inputStream.available()];
						inputStream.read(image);
						inputStream.close();
						return image;
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return null;
	}




}
